package com.ithaipeng.redanttakeaway.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ithaipeng.redanttakeaway.pojo.Category;
import com.ithaipeng.redanttakeaway.service.ICategoryService;
import com.ithaipeng.redanttakeaway.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;
    @GetMapping("/page")
    public Result<Page<Category>> selectByPage(@RequestParam(required = false,defaultValue = "1")Integer page,
                                     @RequestParam(required = false,defaultValue = "10")Integer pageSize){
        Page<Category> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,queryWrapper);
        return Result.success(pageInfo);
    }
    /**
     * 添加分类等
     */
    @PostMapping
    public Result<String> save(@RequestBody Category category){
        boolean isSuccess = categoryService.save(category);
        if (isSuccess){
            return Result.success("添加分类成功!");
        }
        return Result.error("添加分类失败!");
    }
    /**
     * 修改菜品，PUT请求
     */
    @PutMapping
    public Result<String> upDate(@RequestBody Category category){
        boolean isSuccess = categoryService.updateById(category);
        if (isSuccess){
            return Result.success("修改信息成功!");
        }
        return Result.error("修改信息失败!");
    }
    @DeleteMapping
    public Result<String> remove(Long id){
        categoryService.delete(id);
        return Result.success("该分类已删除成功");
    }
    @GetMapping("/list")
    public Result<List<Category>> listCategory( Category category){
        log.info("category:--->{}",category.toString());
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper=new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryService.list(categoryLambdaQueryWrapper);
        if(!categoryList.isEmpty()){
            return Result.success(categoryList);
        }
        return Result.error("查询失败");
    }
}
